home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 2004 #2 / K-CD-2-2004.ISO / OpenOffice Sv / f_0397 / python-core-2.2.2 / lib / site.py < prev    next >
Encoding:
Python Source  |  2003-07-18  |  10.1 KB  |  331 lines

  1. """Append module search paths for third-party packages to sys.path.
  2.  
  3. ****************************************************************
  4. * This module is automatically imported during initialization. *
  5. ****************************************************************
  6.  
  7. In earlier versions of Python (up to 1.5a3), scripts or modules that
  8. needed to use site-specific modules would place ``import site''
  9. somewhere near the top of their code.  Because of the automatic
  10. import, this is no longer necessary (but code that does it still
  11. works).
  12.  
  13. This will append site-specific paths to to the module search path.  On
  14. Unix, it starts with sys.prefix and sys.exec_prefix (if different) and
  15. appends lib/python<version>/site-packages as well as lib/site-python.
  16. On other platforms (mainly Mac and Windows), it uses just sys.prefix
  17. (and sys.exec_prefix, if different, but this is unlikely).  The
  18. resulting directories, if they exist, are appended to sys.path, and
  19. also inspected for path configuration files.
  20.  
  21. A path configuration file is a file whose name has the form
  22. <package>.pth; its contents are additional directories (one per line)
  23. to be added to sys.path.  Non-existing directories (or
  24. non-directories) are never added to sys.path; no directory is added to
  25. sys.path more than once.  Blank lines and lines beginning with
  26. '#' are skipped. Lines starting with 'import' are executed.
  27.  
  28. For example, suppose sys.prefix and sys.exec_prefix are set to
  29. /usr/local and there is a directory /usr/local/lib/python1.5/site-packages
  30. with three subdirectories, foo, bar and spam, and two path
  31. configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
  32. following:
  33.  
  34.   # foo package configuration
  35.   foo
  36.   bar
  37.   bletch
  38.  
  39. and bar.pth contains:
  40.  
  41.   # bar package configuration
  42.   bar
  43.  
  44. Then the following directories are added to sys.path, in this order:
  45.  
  46.   /usr/local/lib/python1.5/site-packages/bar
  47.   /usr/local/lib/python1.5/site-packages/foo
  48.  
  49. Note that bletch is omitted because it doesn't exist; bar precedes foo
  50. because bar.pth comes alphabetically before foo.pth; and spam is
  51. omitted because it is not mentioned in either path configuration file.
  52.  
  53. After these path manipulations, an attempt is made to import a module
  54. named sitecustomize, which can perform arbitrary additional
  55. site-specific customizations.  If this import fails with an
  56. ImportError exception, it is silently ignored.
  57.  
  58. """
  59.  
  60. import sys, os
  61.  
  62.  
  63. def makepath(*paths):
  64.     dir = os.path.abspath(os.path.join(*paths))
  65.     return dir, os.path.normcase(dir)
  66.  
  67. for m in sys.modules.values():
  68.     if hasattr(m, "__file__") and m.__file__:
  69.         m.__file__ = os.path.abspath(m.__file__)
  70. del m
  71.  
  72. # This ensures that the initial path provided by the interpreter contains
  73. # only absolute pathnames, even if we're running from the build directory.
  74. L = []
  75. _dirs_in_sys_path = {}
  76. for dir in sys.path:
  77.     # Filter out paths that don't exist, but leave in the empty string
  78.     # since it's a special case. We also need to special-case the Mac,
  79.     # as file names are allowed on sys.path there.
  80.     if sys.platform != 'mac':
  81.         if dir and not os.path.isdir(dir):
  82.             continue
  83.     else:
  84.         if dir and not os.path.exists(dir):
  85.             continue
  86.     dir, dircase = makepath(dir)
  87.     if not _dirs_in_sys_path.has_key(dircase):
  88.         L.append(dir)
  89.         _dirs_in_sys_path[dircase] = 1
  90. sys.path[:] = L
  91. del dir, L
  92.  
  93. # Append ./build/lib.<platform> in case we're running in the build dir
  94. # (especially for Guido :-)
  95. if (os.name == "posix" and sys.path and
  96.     os.path.basename(sys.path[-1]) == "Modules"):
  97.     from distutils.util import get_platform
  98.     s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
  99.     s = os.path.join(os.path.dirname(sys.path[-1]), s)
  100.     sys.path.append(s)
  101.     del get_platform, s
  102.  
  103. def _init_pathinfo():
  104.     global _dirs_in_sys_path
  105.     _dirs_in_sys_path = d = {}
  106.     for dir in sys.path:
  107.         if dir and not os.path.isdir(dir):
  108.             continue
  109.         dir, dircase = makepath(dir)
  110.         d[dircase] = 1
  111.  
  112. def addsitedir(sitedir):
  113.     global _dirs_in_sys_path
  114.     if _dirs_in_sys_path is None:
  115.         _init_pathinfo()
  116.         reset = 1
  117.     else:
  118.         reset = 0
  119.     sitedir, sitedircase = makepath(sitedir)
  120.     if not _dirs_in_sys_path.has_key(sitedircase):
  121.         sys.path.append(sitedir)        # Add path component
  122.     try:
  123.         names = os.listdir(sitedir)
  124.     except os.error:
  125.         return
  126.     names.sort()
  127.     for name in names:
  128.         if name[-4:] == os.extsep + "pth":
  129.             addpackage(sitedir, name)
  130.     if reset:
  131.         _dirs_in_sys_path = None
  132.  
  133. def addpackage(sitedir, name):
  134.     global _dirs_in_sys_path
  135.     if _dirs_in_sys_path is None:
  136.         _init_pathinfo()
  137.         reset = 1
  138.     else:
  139.         reset = 0
  140.     fullname = os.path.join(sitedir, name)
  141.     try:
  142.         f = open(fullname)
  143.     except IOError:
  144.         return
  145.     while 1:
  146.         dir = f.readline()
  147.         if not dir:
  148.             break
  149.         if dir[0] == '#':
  150.             continue
  151.         if dir.startswith("import"):
  152.             exec dir
  153.             continue
  154.         if dir[-1] == '\n':
  155.             dir = dir[:-1]
  156.         dir, dircase = makepath(sitedir, dir)
  157.         if not _dirs_in_sys_path.has_key(dircase) and os.path.exists(dir):
  158.             sys.path.append(dir)
  159.             _dirs_in_sys_path[dircase] = 1
  160.     if reset:
  161.         _dirs_in_sys_path = None
  162.  
  163. prefixes = [sys.prefix]
  164. if sys.exec_prefix != sys.prefix:
  165.     prefixes.append(sys.exec_prefix)
  166. for prefix in prefixes:
  167.     if prefix:
  168.         if os.sep == '/':
  169.             sitedirs = [os.path.join(prefix,
  170.                                      "lib",
  171.                                      "python" + sys.version[:3],
  172.                                      "site-packages"),
  173.                         os.path.join(prefix, "lib", "site-python")]
  174.         else:
  175.             sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
  176.         for sitedir in sitedirs:
  177.             if os.path.isdir(sitedir):
  178.                 addsitedir(sitedir)
  179.  
  180. _dirs_in_sys_path = None
  181.  
  182.  
  183. # Define new built-ins 'quit' and 'exit'.
  184. # These are simply strings that display a hint on how to exit.
  185. if os.sep == ':':
  186.     exit = 'Use Cmd-Q to quit.'
  187. elif os.sep == '\\':
  188.     exit = 'Use Ctrl-Z plus Return to exit.'
  189. else:
  190.     exit = 'Use Ctrl-D (i.e. EOF) to exit.'
  191. import __builtin__
  192. __builtin__.quit = __builtin__.exit = exit
  193. del exit
  194.  
  195. # interactive prompt objects for printing the license text, a list of
  196. # contributors and the copyright notice.
  197. class _Printer:
  198.     MAXLINES = 23
  199.  
  200.     def __init__(self, name, data, files=(), dirs=()):
  201.         self.__name = name
  202.         self.__data = data
  203.         self.__files = files
  204.         self.__dirs = dirs
  205.         self.__lines = None
  206.  
  207.     def __setup(self):
  208.         if self.__lines:
  209.             return
  210.         data = None
  211.         for dir in self.__dirs:
  212.             for file in self.__files:
  213.                 file = os.path.join(dir, file)
  214.                 try:
  215.                     fp = open(file)
  216.                     data = fp.read()
  217.                     fp.close()
  218.                     break
  219.                 except IOError:
  220.                     pass
  221.             if data:
  222.                 break
  223.         if not data:
  224.             data = self.__data
  225.         self.__lines = data.split('\n')
  226.         self.__linecnt = len(self.__lines)
  227.  
  228.     def __repr__(self):
  229.         self.__setup()
  230.         if len(self.__lines) <= self.MAXLINES:
  231.             return "\n".join(self.__lines)
  232.         else:
  233.             return "Type %s() to see the full %s text" % ((self.__name,)*2)
  234.  
  235.     def __call__(self):
  236.         self.__setup()
  237.         prompt = 'Hit Return for more, or q (and Return) to quit: '
  238.         lineno = 0
  239.         while 1:
  240.             try:
  241.                 for i in range(lineno, lineno + self.MAXLINES):
  242.                     print self.__lines[i]
  243.             except IndexError:
  244.                 break
  245.             else:
  246.                 lineno += self.MAXLINES
  247.                 key = None
  248.                 while key is None:
  249.                     key = raw_input(prompt)
  250.                     if key not in ('', 'q'):
  251.                         key = None
  252.                 if key == 'q':
  253.                     break
  254.  
  255. __builtin__.copyright = _Printer("copyright", sys.copyright)
  256. if sys.platform[:4] == 'java':
  257.     __builtin__.credits = _Printer(
  258.         "credits",
  259.         "Jython is maintained by the Jython developers (www.jython.org).")
  260. else:
  261.     __builtin__.credits = _Printer("credits", """\
  262. Thanks to CWI, CNRI, BeOpen.com, Digital Creations and a cast of thousands
  263. for supporting Python development.  See www.python.org for more information.""")
  264. here = os.path.dirname(os.__file__)
  265. __builtin__.license = _Printer(
  266.     "license", "See http://www.python.org/%.3s/license.html" % sys.version,
  267.     ["LICENSE.txt", "LICENSE"],
  268.     [os.path.join(here, os.pardir), here, os.curdir])
  269.  
  270.  
  271. # Define new built-in 'help'.
  272. # This is a wrapper around pydoc.help (with a twist).
  273.  
  274. class _Helper:
  275.     def __repr__(self):
  276.         return "Type help() for interactive help, " \
  277.                "or help(object) for help about object."
  278.     def __call__(self, *args, **kwds):
  279.         import pydoc
  280.         return pydoc.help(*args, **kwds)
  281.  
  282. __builtin__.help = _Helper()
  283.  
  284.  
  285. # Set the string encoding used by the Unicode implementation.  The
  286. # default is 'ascii', but if you're willing to experiment, you can
  287. # change this.
  288.  
  289. encoding = "ascii" # Default value set by _PyUnicode_Init()
  290.  
  291. if 0:
  292.     # Enable to support locale aware default string encodings.
  293.     import locale
  294.     loc = locale.getdefaultlocale()
  295.     if loc[1]:
  296.         encoding = loc[1]
  297.  
  298. if 0:
  299.     # Enable to switch off string to Unicode coercion and implicit
  300.     # Unicode to string conversion.
  301.     encoding = "undefined"
  302.  
  303. if encoding != "ascii":
  304.     # On Non-Unicode builds this will raise an AttributeError...
  305.     sys.setdefaultencoding(encoding) # Needs Python Unicode build !
  306.  
  307. #
  308. # Run custom site specific code, if available.
  309. #
  310. try:
  311.     import sitecustomize
  312. except ImportError:
  313.     pass
  314.  
  315. #
  316. # Remove sys.setdefaultencoding() so that users cannot change the
  317. # encoding after initialization.  The test for presence is needed when
  318. # this module is run as a script, because this code is executed twice.
  319. #
  320. if hasattr(sys, "setdefaultencoding"):
  321.     del sys.setdefaultencoding
  322.  
  323. def _test():
  324.     print "sys.path = ["
  325.     for dir in sys.path:
  326.         print "    %s," % `dir`
  327.     print "]"
  328.  
  329. if __name__ == '__main__':
  330.     _test()
  331.